Skip to content

feat(scan): Support split and parallel scans - Part-3: lazy split and group planning - #1113

Merged
wgtmac merged 5 commits into
apache:mainfrom
kamcheungting-db:feat/file-scan-task-groups
Nov 22, 2026
Merged

wgtmac merged 5 commits into
apache:mainfrom
kamcheungting-db:feat/file-scan-task-groups

Conversation

@kamcheungting-db

@kamcheungting-db kamcheungting-db commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Adds task-group planning for parallel scans, on top of the byte ranges from #976 and the range-aware Parquet reads from #1002:

  • DataTableScan::PlanTasksStream() — lazy, fallible stream of FileScanTaskGroup
  • DataTableScan::PlanTasks() — the same, collected into a vector

Eligible Parquet files are split into byte ranges, and the tasks are packed into groups of roughly read.split.target-size bytes.

How it works

          PlanFilesStream()
                 |
                 v
          Whole Parquet file larger than target? -- no --> keep task as is
                 |
                yes
                 v
          Valid manifest split_offsets?
             | yes                    | no
             v                        v
          merge intervals          fixed-size byte ranges
          toward target            (shorter final range if needed)
                 |                    |
                 +---------+----------+
                           v
                 pack tasks into groups
                           |
                           v
                  FileScanTaskGroup stream

Packing — follows Java Iceberg’s first-fit and eviction rules:

  • task weight = max(range bytes + delete content bytes, (1 + delete files) * open-file-cost); a deletion vector counts its blob size, not its container file size
  • a task joins the first open group that still fits
  • at most planning-lookback groups stay open; when a new one opens, the largest open group is closed first
  • at most 1,024 tasks per group; a task heavier than the target becomes its own group

Files that stay whole: files at or below the target size, non-Parquet files, and Parquet files whose valid manifest offsets yield only one range.

Settings

Property Default Resolves from
read.split.target-size 128 MB scan option > table property > default
read.split.planning-lookback 10 same
read.split.open-file-cost 4 MB same

Malformed or invalid values fail planning before any planning work starts.

Stream behavior

Single pass, lazy, owns the underlying task stream and its metrics, and can outlive the scan. An executor set with PlanWith() is borrowed and must stay alive until the group stream is destroyed. Destroying the stream mid-consumption releases all planning resources. The stream retains the current file’s remaining splits across calls to Next(). Splitting requires no data-file I/O or Parquet bundle registration.

Tests

  • table_test (core-only, includes ScanTaskPlanningTest): split coverage and merging, delete files and residual filters carried into every split, mixed Parquet/Avro groups, the Java weight formula, group packing (first fit, lookback, 1,024 cap, oversized singleton), settings precedence and errors, incremental consumption, early destruction.
  • Bundled scan_test, across manifest format versions: split offsets used with no footer read (the file path does not exist), fixed-size ranges for missing or invalid offsets, files at or below target stay whole, every row read exactly once across splits, scan option beats table property, no-snapshot scans, delete files carried into every split.

pre-commit is clean.

Related

Part 1 #976 · Part 2a #1002 · Part 2b #1062 · Part 2c #1065. The bounded parallel reader and end-to-end validation follow in later parts.

@kamcheungting-db
kamcheungting-db force-pushed the feat/file-scan-task-groups branch from fa8ac0a to 79e66ba Compare November 11, 2026 16:27
Comment thread src/iceberg/scan_task_planning.cc Resolved
Comment thread src/iceberg/scan_task_planning.cc Resolved
@wgtmac
wgtmac force-pushed the feat/file-scan-task-groups branch from 9241812 to 8a750fa Compare November 22, 2026 15:26

@wgtmac wgtmac left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall it looks good to me. I pushed a fix for one case where returning a group could drop the remaining splits of the current file. I also aligned the fallback with Java: when manifest offsets are missing or unusable, large Parquet files use target-sized byte ranges and small files stay whole. The reader already assigns row groups to those ranges, so we could remove the planner’s footer reads and split-policy registry.

@wgtmac
wgtmac merged commit 4002e31 into apache:main Nov 22, 2026
15 checks passed
wgtmac pushed a commit that referenced this pull request Dec 1, 2026
…el Arrow reader (#1167)

## What this PR does

Adds `ParallelScanReader` (`iceberg/data/parallel_scan_reader.h`), which reads the groups of a `FileScanTaskGroupStream` (from #1113) with a fixed set of workers on a caller-provided executor and returns one Arrow C stream.

```cpp
auto groups = scan->PlanTasksStream();
auto stream = ParallelScanReader::Open(
    std::move(*groups), {.reader_options = reader_options,
                         .executor = &executor,
                         .worker_count = 8,
                         .max_queued_batches = 16,
                         .max_queued_bytes = 64 << 20});
```

## How it works

```
                          ParallelScanReader::Open(groups, options)
                                       │ validate options, build the projected Arrow schema,
                                       │ make one FileScanTaskReader + ArrowBatchSizer per worker
                                       v
  ┌──────────────────────────────── workers 1..N ────────────────────────────────┐
  │                                                                              │
  │  ClaimGroup()                                                                │
  │    yield if busy; otherwise call groups->Next() outside all locks            │
  │    (one worker at a time)          │                                         │
  │                                    ├─ group ──> release token, read it       │
  │                                    ├─ end   ──> destroy group stream, done   │
  │                                    └─ error ──> Stop(error)                  │
  │                                                                              │
  │  for each task in the group, in order:                                       │
  │    reader.Open(task) ──> check task schema == projected schema               │
  │      for each batch:                                                         │
  │        sizer.Measure(batch)   preflight overflow checks, then sum buffer     │
  │                               spans (children, dictionaries, variadic)       │
  │        TryEnqueue(worker)      admit the head ticket if it fits;             │
  │                                otherwise keep the batch and yield            │
  └───────────────────────────────────────┬──────────────────────────────────────┘
                                          v
                ┌──────────── output queue ─────────────┐
                │ admit when:                           │
                │   count < max_queued_batches  AND     │
                │   charge <= max_queued_bytes:         │
                │     queued + charge <= budget         │
                │   charge >  max_queued_bytes:         │
                │     queue is empty (sole batch)       │
                └───────────────────┬───────────────────┘
                                    v
                    get_next ──> pop front, subtract charge, wake producers
                                 (caller owns the array from here)
                    end of stream when all workers finished and the queue is empty

  Stop(error)  (first error wins)        release() between callbacks
    stop new work                           stop new work
    release queued batches                  release queued batches
    get_next returns EIO;                   wait for running callbacks and submissions
    get_last_error() gives the message      destroy the group stream
                                            returned arrays stay valid
```

- **Planning.** Workers claim groups through a planning token: only one calls the single-pass group stream at a time, and never under a lock. The stream is destroyed as soon as it is exhausted, so planning metrics are reported at EOF.
- **Reading.** Each worker owns a `FileScanTaskReader`. Residual filters are always enforced (`apply_residuals` is forced on). The projected schema must contain every field referenced by the task residual. Each task stream's schema is compared with the projected schema before its batches are read.
- **Queue.** Batches enter a queue bounded by count (`max_queued_batches`) and by charged bytes (`max_queued_bytes`). Producers are admitted in FIFO order. A batch larger than the byte budget enters only an empty queue, as its sole batch. Zero-byte batches still count toward the batch limit. A worker holds at most one completed batch while it waits and yields its executor thread.
- **Charging.** `ArrowBatchSizer` currently estimates a batch's charge as the checked sum of the spans of all present buffers, including children, dictionaries, and variadic buffers. Before nanoarrow sizes anything, it checks offsets, lengths, buffer, child, and dictionary counts, and every layout-dependent size product for overflow. List views and run-end encoded arrays are rejected.
- **Errors and release.** The first planning, read, schema, or sizing error stops new work, releases queued batches, and is returned from the next `get_next` as `EIO`. For task read errors, `get_last_error()` includes the file path and, for splits, the byte range. Releasing the stream between callbacks stops the workers, releases batches that were not returned, and waits for running callbacks; batches already returned stay valid. Queued executor callbacks that run later see the stop flag and return.

`iceberg_data` now links `Threads::Threads` unconditionally, including with `ICEBERG_SPDLOG=OFF`.

The queue limits bound admission, not process memory: format reader buffers, delete indexes, and arrays already returned to the caller are outside the budget. The header documents this, the per-worker memory estimate, and the preconditions (registered format factories, a `FileIO` that supports concurrent reads, immutable task metadata, a read executor that outlives the stream and its accepted callbacks, a planning executor that outlives the stream, and matching `case_sensitive`).

## Tests

The parallel reader and batch sizer tests are part of `scan_test` (`ICEBERG_BUILD_BUNDLE=ON`). The parallel reader unit tests use hand-built groups and a scoped fake reader registered for Parquet and Avro:

- zero, one, and many groups; 1 versus N workers return the same rows; mixed formats in a group; residuals enforced
- task-local order across interleaved groups
- executor submission failures, planning handoff, and workers yielding under queue backpressure
- schema mismatch, open failure, read failure (with the file range in the message), reader exceptions, and planning failures and exceptions; errors are sticky
- bytes binding before count, count binding before bytes, zero-byte batches, oversized singletons, and mixed small and oversized batches
- releasing between callbacks while producers wait, releasing without reading, and callers keeping a returned array after release; every fake array is released exactly once
- the group stream is destroyed at the end of planning, and its destructor can query metrics
- `ArrowBatchSizer`: fixed width, sliced, variable width, nested, dictionary, string view, zero-column structs, unsupported list views, and overflow and malformed-count rejections

A planned historical scan also checks that a missing residual field is reported rather than silently dropping rows. The bundle-enabled `scan_test` passes locally. Real Parquet and Avro tables are covered in Part-5. `pre-commit` is clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants